package cn.com.headfree.salary.controller;

import cn.com.headfree.base.controller.ExBaseController;
import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.entity.*;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.point.service.PointRuleService;
import cn.com.headfree.point.service.PointSetOverService;
import cn.com.headfree.point.service.RuleElementService;
import cn.com.headfree.salary.service.*;
import cn.com.headfree.util.ExcelExportUtil;
import cn.com.headfree.util.SysDictionaryUtil;
import cn.com.headfree.vo.*;
import com.gta.edu.sdk.common.dto.Page;
import com.gta.edu.sdk.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 薪档调整
 */
@Controller
@RequestMapping(value = "/salary", produces = "application/json;charset=UTF-8")
public class SalaryController extends ExBaseController {
	private static final Logger LOG = LogManager.getLogger(SalaryController.class);

	@Autowired
	private IUserDataInfoService userDataInfoService;

	@Autowired
	private TSalaryHandleService tSalaryHandleService;

	@Autowired
	private SalaryService salaryService;

	@Autowired
	private ExportWordUserDataInfoService exportWordUserDataInfoService;

	@Autowired
	private WordExportService wordExportService;

	@Autowired
	private PointSetOverService pointSetOverService;

	@Autowired
	private PointRuleService pointRuleService;

	@Autowired
	private RuleElementService ruleElementService;

	// 年度绩效
	@Value("${t_year_effect_info}")
	private String t_year_effect_info;
	// 学历信息
	@Value("${t_educate_info}")
	private String t_educate_info;
	// 专业技术资格
	@Value("${t_pro_tec_info}")
	private String t_pro_tec_info;
	// 技能等级信息
	@Value("${t_skill_level_info}")
	private String t_skill_level_info;
	// 专家人才称号
	@Value("${t_expert_title_info}")
	private String t_expert_title_info;
	// 学术成果
	@Value("${t_acade_achive_info}")
	private String t_acade_achive_info;
	// 专利信息
	@Value("${t_patent_info}")
	private String t_patent_info;
	// 技艺革新信息
	@Value("${t_tec_innov_info}")
	private String t_tec_innov_info;
	// 竞赛考试信息
	@Value("${t_contest_info}")
	private String t_contest_info;
	// 科技管理及创新成果
	@Value("${t_tec_man_innov}")
	private String t_tec_man_innov;
	// 个人荣誉
	@Value("${t_honor_info}")
	private String t_honor_info;
	// 員工流動
	@Value("${t_employee_mobility}")
	private String t_employee_mobility;
	// 技术标准
	@Value("${t_tec_standard_info}")
	private String t_tec_standard_info;
	// 工龄
	@Value("${t_employ_length}")
	private String t_employ_length;

	@Value("${d_value}")
	private double d_value;

	/**
	 * 用户计算积分的时间，此时间组合为了适应之前汪发勇写的取学历、专业技术资格、技能等级的查询方法
	 */
//    Calendar date = Calendar.getInstance();
//    int currentYear = Integer.valueOf(date.get(Calendar.YEAR));
//    int lastYear = currentYear;
//    String startDate = lastYear + "-01-01";
//    String endDate = lastYear + "-12-31";
//
//    //前年
//    int beforeYear = lastYear - 1;
//    String beforestartDate = beforeYear + "-01-01";
//    String beforendDate = beforeYear + "-12-31";


	//增加薪档单个申报功能
	@RequestMapping("/saveSalaryInfoByErpNo")
	public ResultData saveSalaryInfoByErpNo(HttpServletRequest request, @RequestBody TSalaryInfo tSalaryInfo) {
		ResultData rs = new ResultData();
		User user = this.getLoginUserInfo(request);
		try {
			//默认申报上年度
			Calendar date = Calendar.getInstance();
			int currentYear = Integer.valueOf(date.get(Calendar.YEAR));
			int year = currentYear - 1;
			TPointSetOver over = new TPointSetOver();
			over.setYear(year);
			over.setOrgId(tSalaryInfo.getOrgId());
			List<TPointSetOver> overs = pointSetOverService.findPointSetOverByYearAndOrgId(over);
			if (overs != null && overs.size() > 0) {
				rs.setSuccess(false);
				rs.setErrorMsg("当前年度薪档申报已结束");
			} else {
				// 根据用户组织查找用户对应的积分规则
				List<TPointRuleInfo> ruleInfos = pointRuleService.findStartUsePointRuleInfoList(tSalaryInfo.getOrgId());
				if (ruleInfos != null && ruleInfos.size() > 0) {
					salaryService.saveSalaryInfoByErpNo(user,year,tSalaryInfo.getErpNo(),ruleInfos.get(0).getId(),tSalaryInfo.getOrgId());
					rs.setData("申报成功");
				} else {
					rs.setSuccess(false);
					rs.setErrorMsg("当前未启用积分规则，无法申报");
				}
			}
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("薪档申报 -> 失败！");
			e.printStackTrace();
		}
		return rs;
	}





	//增加薪档全员申报按钮
	@RequestMapping("/saveAllSalaryInfo")
	public ResultData saveAllSalaryInfo(HttpServletRequest request, Integer year) {
		ResultData rs = new ResultData();
		User user = this.getLoginUserInfo(request);
		try {
			//只能申报上年度，如果不是，驳回
			Calendar date = Calendar.getInstance();
			int currentYear = Integer.valueOf(date.get(Calendar.YEAR));
			int appYear = currentYear - 1;
			if(appYear!=year){
				rs.setData("无法申报该年度，只能申报当前年度的上一年度");
				rs.setSuccess(false);
				return rs;
			}

			TPointSetOver over = new TPointSetOver();
			over.setYear(year);
			over.setOrgId(user.getBaseOrgId());
			List<TPointSetOver> overs = pointSetOverService.findPointSetOverByYearAndOrgId(over);
			if (overs != null && overs.size() > 0) {
				rs.setSuccess(false);
				rs.setErrorMsg("当前年度薪档申报已结束");
			} else {
				// 根据用户组织查找用户对应的积分规则
				List<TPointRuleInfo> ruleInfos = pointRuleService.findStartUsePointRuleInfoList(user.getBaseOrgId());
				if (ruleInfos != null && ruleInfos.size() > 0) {
					salaryService.saveAllSalaryInfo(year,user,ruleInfos.get(0).getId());
					rs.setData("申报完成");
					LOG.info("薪档全员批量申报 -> 成功");
				} else {
					rs.setSuccess(false);
					rs.setErrorMsg("当前未启用积分规则，无法申报");
				}
			}
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("薪档全员批量申报 -> 失败！");
			e.printStackTrace();
		}
		return rs;
	}




	/**
	 * 保存
	 */
	@RequestMapping("/saveSalaryInfo")
	@ResponseBody
	public ResultData saveSalaryInfo(HttpServletRequest request, TSalaryInfo tSalaryInfo) {
		ResultData rs = new ResultData();
		User user = this.getLoginUserInfo(request);
		try {
			tSalaryInfo.setErpNo(user.getFax());
			tSalaryInfo.setUserName(user.getName());
			List<TSalaryInfo> salaryInfos = salaryService.judge(tSalaryInfo);
			TPointSetOver over = new TPointSetOver();
			over.setYear(tSalaryInfo.getYear());
			over.setOrgId(user.getBaseOrgId());
			List<TPointSetOver> overs = pointSetOverService.findPointSetOverByYearAndOrgId(over);
			if (salaryInfos != null && salaryInfos.size() > 0) {
				rs.setSuccess(false);
				rs.setErrorMsg("当前年度已申请调整");
			} else if (overs != null && overs.size() > 0) {
				rs.setSuccess(false);
				rs.setErrorMsg("当前年度薪档申报已结束");
			} else {
				// 根据用户组织查找用户对应的积分规则
				List<TPointRuleInfo> ruleInfos = pointRuleService.findStartUsePointRuleInfoList(user.getBaseOrgId());
				if (ruleInfos != null && ruleInfos.size() > 0) {
					tSalaryInfo.setErpNo(user.getFax());
					tSalaryInfo.setUserName(user.getName());
					tSalaryInfo.setOrgId(user.getBaseOrgId());
					tSalaryInfo.setOrgName(user.getBaseOrgName());
					tSalaryInfo.setRuleId(ruleInfos.get(0).getId());
					salaryService.saveSalaryInfo(tSalaryInfo);
					rs.setSuccess(true);
					rs.setData(ruleInfos.get(0).getId());
					LOG.info("保存成功");
				} else {
					rs.setSuccess(false);
					rs.setErrorMsg("当前未启用积分规则，无法申报");
				}
			}
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("保存失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 分页查询列表
	 *
	 * @param page
	 * @param year
	 * @return
	 */
	@RequestMapping("/getPageSalaryInfo")
	@ResponseBody
	public ResultData getPageSalaryInfo(Page<TSalaryInfo> page, String year, HttpServletRequest request) {
		ResultData rs = new ResultData();
		try {
			User user = this.getLoginUserInfo(request);
			salaryService.getPageSalaryInfo(page, year, user);
			rs.setData(page);
			LOG.info("查询成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查询失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 基本情况
	 *
	 * @param erpNo
	 * @return
	 */
	@RequestMapping("/getTEmpBaseInfoForSalary")
	@ResponseBody
	public ResultData getTEmpBaseInfoForSalary(String erpNo) {
		ResultData rs = new ResultData();
		try {
			TEmpBaseInfo tEmpBaseInfo = userDataInfoService.getBaseInfoByErpNo(erpNo);
			rs.setSuccess(true);
			rs.setData(tEmpBaseInfo);
			LOG.info("查找个人基本情况成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找个人基本情况失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 学历
	 */
	@RequestMapping("/getEducateInfoForSalary")
	@ResponseBody
	public ResultData getEducateInfoForSalary(HttpServletRequest request, String erpNo, String salaryId, String ruleId,
			int year,boolean salary) {
		ResultData rs = new ResultData();
		try {
			// 上个年度学历对应分值
			lastEduPoint = 0.0;
			lastDreePoint = 0.0;
			// 当前申请的学历分值
			currentEduPoint = 0.0;
			currentDreePoint = 0.0;
			User user = this.getLoginUserInfo(request);
			List<EducateInfoVo> educateInfos ;
			if (salary) {
				//已添加薪档数据
				educateInfos = userDataInfoService.getEducateInfoByErpNoInSalary(erpNo, salaryId, year,t_educate_info);
			} else {
				educateInfos = userDataInfoService.getEducateInfoByErpNo(erpNo, salaryId, year);
			}

			if (educateInfos != null && educateInfos.size() > 0) {
				educateInfos = computeEducatePoint(user, educateInfos, ruleId, erpNo, ruleId, year);
			}
			rs.setSuccess(true);
			rs.setData(educateInfos);
			LOG.info("查找学历信息成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找学历信息失败！");
			e.printStackTrace();
		}
		return rs;
	}

	// 上个年度学历对应分值
	double lastEduPoint = 0.0;
	double lastDreePoint = 0.0;
	// 当前申请的学历分值
	double currentEduPoint = 0.0;
	double currentDreePoint = 0.0;

	/**
	 * 根据学历规则计算得分
	 *
	 * @param ruleId
	 */
	private List<EducateInfoVo> computeEducatePoint(User user, List<EducateInfoVo> educateInfos, String ruleId,
			String erpNo, String salaryId, int year) {
		// 1、学历角度，分为四段中专以下（>=40）"^(([3-9]\\d)|(1([0-7]\\d)))$"、大学专科（>=30&&<20）、博士研究生（>10&&<14）、硕士（>=14&&<20）
		// 2、学位角度 学士学位（包含 4）、双学士（5）、博士学位（包含 "2")、硕士学位（包含"3"）
		// 3、按照区间
		try {

			// 前年
			int beforeYear = year - 1;
			String beforestartDate = beforeYear + "-01-01";
			String beforendDate = beforeYear + "-12-31";

			// 1.查询新增学历获取积分的配置规则
			List<TRuleElementInfo> pointList = userDataInfoService.getTRuleElementInfoByproIdAndMouId(ruleId,
					t_educate_info, user.getBaseOrgId());
			// pointList.sort(Comparator.comparing(TRuleElementInfo::getElementLevel));//升序
			// 声明正则表达式
			final Pattern pattern = Pattern.compile("");
			// 判断系统是否已经配置过学历积分规则
			if (pointList.size() > 0) {
				// 2.查询上一年度获取的学历 ->改为   查去年以前获取的学历
				List<EducateInfoVo> beforeEducateInfos = userDataInfoService.getEducateInfoByErpNo(erpNo, salaryId,
						beforestartDate, beforendDate);
				// 之前学历/学位积分
				if (beforeEducateInfos != null && beforeEducateInfos.size() > 0) {
					double[] lastArr = getPointEduOrDrgeeV(beforeEducateInfos, pointList);
					lastEduPoint = lastArr[0];
					lastDreePoint = lastArr[1];
					LOG.info("上一年度学历最高分：" + lastEduPoint + "," + "学位最高分：" + lastDreePoint);
					// -------------------------
//                    //对学历积分排序
//                    beforeEducateInfos = beforeEducateInfos.stream().sorted(Comparator.nullsLast(Comparator.comparing(EducateInfoVo::getEducCode).reversed())).collect(Collectors.toList());
//                    //此时之前获得学历最高分为
//                    lastEduPoint = beforeEducateInfos.get(0).getPoint();
////                    lastEduPoint = Double.parseDouble(beforeEducateInfos.get(0).getPoint());
//                    //对学历积分排序
//                    beforeEducateInfos = beforeEducateInfos.stream().sorted(Comparator.nullsLast(Comparator.comparing(EducateInfoVo::getDegreeCode).reversed())).collect(Collectors.toList());
//                    //此时之前获得学位最高分为
//                    lastDreePoint = beforeEducateInfos.get(0).getPoint();
////                    lastDreePoint = Double.parseDouble(beforeEducateInfos.get(0).getPoint());
					// ------------------------------------------

				}
				double[] current = getPointEduOrDrgeeV(educateInfos, pointList);
				currentEduPoint = current[0];
				currentDreePoint = current[1];
				LOG.info("本年度学历最高分：" + currentEduPoint + "," + "学位最高分：" + currentDreePoint);
				// -----------------------------------------------------
//                //当前学历/学位最高分
//                List<EducateInfoVo> educList = getPointEduOrDrgee(educateInfos, pointList);
//                educList = educList.stream().sorted(Comparator.nullsLast(Comparator.comparing(EducateInfoVo::getEducCode).reversed())).collect(Collectors.toList());
//                //此时之前获得学历最高分为
//                //currentEduPoint = Double.parseDouble(educList.get(0).getPoint());
//                currentEduPoint = educList.get(0).getPoint();
//                //对学位积分排序
//                educList = educList.stream().sorted(Comparator.nullsLast(Comparator.comparing(EducateInfoVo::getDegreeCode).reversed())).collect(Collectors.toList());
//                //此时之前获得学位最高分为
////                currentDreePoint = Double.parseDouble(educList.get(0).getPoint());
//                currentDreePoint = educList.get(0).getPoint();
				// -----------------------------------------------------

				// 将不加分的项设置为null
				educateInfos.stream().forEach(p -> {
					p.setPoint(0.0);
				});

				if (lastDreePoint == 0.0 && lastEduPoint == 0.0) {
					// 表示当前用户往昔没有学历信息，视为新增，此时取学历/学位最高分
					if (currentEduPoint >= currentDreePoint) {
						educateInfos.get(0).setPoint(currentEduPoint);
					} else {
						educateInfos.get(0).setPoint(currentDreePoint);
					}
				}
				// 取差值的最高分
				if ((currentEduPoint - lastEduPoint) > (currentDreePoint - lastDreePoint)) {
					educateInfos.get(0)
							.setPoint((currentEduPoint - lastEduPoint) < 0 ? 0.0 : (currentEduPoint - lastEduPoint));
				} else {
					educateInfos.get(0).setPoint(
							(currentDreePoint - lastDreePoint) < 0 ? 0.0 : (currentDreePoint - lastDreePoint));
				}

//                //取去年分数最高的分
//                if (lastEduPoint > lastDreePoint) {
//                    //当前得分减去去年学历已经增加的最高分
//                    if (currentEduPoint >= currentDreePoint) {
//                        educateInfos.get(0).setPoint((currentEduPoint - lastEduPoint) < 0 ? 0.0 : (currentEduPoint - lastEduPoint));
//                    } else {
//                        educateInfos.get(0).setPoint((currentEduPoint - lastEduPoint) < 0 ? 0.0 : (currentEduPoint - lastEduPoint));
//                    }
//                } else {
//                    //当前得分减去去年学位已经增加的最高分
//                    if (currentEduPoint >= currentDreePoint) {
//                        educateInfos.get(0).setPoint((currentEduPoint - lastDreePoint) < 0 ? 0.0 : (currentEduPoint - lastDreePoint));
//                    } else {
//                        educateInfos.get(0).setPoint((currentDreePoint - lastDreePoint) < 0 ? 0.0 : (currentDreePoint - lastDreePoint));
//                    }
//                }

			}

		} catch (Exception ex) {
			LOG.error("计算学历积分失败：" + ex.getMessage());
		}

		return educateInfos;
	}

	private List<EducateInfoVo> getPointEduOrDrgee(List<EducateInfoVo> beforeEducateInfos,
			List<TRuleElementInfo> pointList) {
		// 对学历进行排序
		List<EducateInfoVo> beforeEducList = beforeEducateInfos.stream().filter(p -> p.getEducCode() != null)
				.collect(Collectors.toList());
		double eduMax = 0.0;
		double drgee = 0.0;
		// 算出之前学历的最高分
		if (beforeEducList != null && beforeEducList.size() > 0) {
			for (int i = 0; i < pointList.size(); i++) {
				String[] pat = pointList.get(i).getElementLevel().split(",");
				// 遍历学位集合
				for (int j = 0; j < beforeEducList.size(); j++) {
					if (!pat[0].startsWith("&")
							&& Pattern.compile(pat[0]).matcher(beforeEducateInfos.get(0).getEducCode()).matches()) {
						// 之前学历赋值分数
						beforeEducList.get(j).setPoint(pointList.get(i).getPoint());

					}
				}
			}
		}

		// eduMax=beforeEducateInfos.stream().filter(p->p.getPoint()!=null).mapToDouble(Comparator.comparing()).sort(Comparator.comparing(EducateInfoVo::getDegreeName));
		eduMax = beforeEducateInfos.stream().filter(p -> p.getPoint() != null).mapToDouble(s -> s.getPoint()).max()
				.isPresent()
						? beforeEducateInfos.stream().filter(p -> p.getPoint() != null).mapToDouble(s -> s.getPoint())
								.max().getAsDouble()
						: 0.0;
		// 对学位进行排序
		List<EducateInfoVo> beforeDgreeList = beforeEducateInfos.stream().filter(p -> p.getDegreeCode() != null)
				.collect(Collectors.toList());
		if (beforeDgreeList != null && beforeDgreeList.size() > 0) {
			// 算出之前获取到的最高学位
			for (int i = 0; i < pointList.size(); i++) {
				String[] pat = pointList.get(i).getElementLevel().split(",");
				// 遍历学位集合
				for (int j = 0; j < beforeDgreeList.size(); j++) {
					if (!pat[1].startsWith("&")) {
						// 包含
						if (beforeDgreeList.get(0).getDegreeCode().startsWith(pat[1].substring(0, 1))) {
							// 之前学历赋值分数
							beforeDgreeList.get(j).setPoint(pointList.get(i).getPoint());
						}
					}
				}
			}
		}
		drgee = beforeDgreeList.stream().filter(p -> p.getPoint() != null).mapToDouble(s -> s.getPoint()).max()
				.isPresent()
						? beforeDgreeList.stream().filter(p -> p.getPoint() != null).mapToDouble(s -> s.getPoint())
								.max().getAsDouble()
						: 0.0;
		LOG.info("学历最高分：" + eduMax + "," + "学位最高分：" + drgee);
		// 对学位进行排序
		// 取学历/学位的最高分
		if (eduMax > drgee) {
			beforeEducateInfos.get(0).setPoint(eduMax);
		} else {
			beforeEducateInfos.get(0).setPoint(drgee);
		}
		return beforeEducateInfos;
	}

	/**
	 * @param beforeEducateInfos
	 * @param pointList
	 * @return
	 */
	private double[] getPointEduOrDrgeeV(List<EducateInfoVo> beforeEducateInfos, List<TRuleElementInfo> pointList) {
		// 对学历进行排序
		List<EducateInfoVo> beforeEducList = beforeEducateInfos.stream().filter(p -> p.getEducCode() != null)
				.collect(Collectors.toList());
		double[] pointArr = new double[2];
		double eduMax = 0.0;
		double drgee = 0.0;
		// 算出之前学历的最高分
		if (beforeEducList != null && beforeEducList.size() > 0) {
			for (int i = 0; i < pointList.size(); i++) {
				String[] pat = pointList.get(i).getElementLevel().split(",");
				// 遍历学位集合
				for (int j = 0; j < beforeEducList.size(); j++) {
					if (!pat[0].startsWith("&")
							&& Pattern.compile(pat[0]).matcher(beforeEducateInfos.get(0).getEducCode()).matches()) {
						// 之前学历赋值分数
						beforeEducList.get(j).setPoint(pointList.get(i).getPoint());

					}
				}
			}
		}

		// eduMax=beforeEducateInfos.stream().filter(p->p.getPoint()!=null).mapToDouble(Comparator.comparing()).sort(Comparator.comparing(EducateInfoVo::getDegreeName));
		eduMax = beforeEducateInfos.stream().filter(p -> p.getPoint() != null).mapToDouble(s -> s.getPoint()).max()
				.isPresent()
						? beforeEducateInfos.stream().filter(p -> p.getPoint() != null).mapToDouble(s -> s.getPoint())
								.max().getAsDouble()
						: 0.0;
		// 对学位进行排序
		List<EducateInfoVo> beforeDgreeList = beforeEducateInfos.stream().filter(p -> p.getDegreeCode() != null)
				.collect(Collectors.toList());
		beforeDgreeList.stream().forEach(tmp -> tmp.setPoint(null));
		if (beforeDgreeList != null && beforeDgreeList.size() > 0) {
			// 算出之前获取到的最高学位
			for (int i = 0; i < pointList.size(); i++) {
				String[] pat = pointList.get(i).getElementLevel().split(",");
				// 遍历学位集合
				for (int j = 0; j < beforeDgreeList.size(); j++) {
					if (!pat[1].startsWith("&")) {
						// 包含
						if (beforeDgreeList.get(0).getDegreeCode().startsWith(pat[1].substring(0, 1))) {
							// 之前学历赋值分数
							beforeDgreeList.get(j).setPoint(pointList.get(i).getPoint());
						}
					}
				}
			}
		}
		drgee = beforeDgreeList.stream().filter(p -> p.getPoint() != null).mapToDouble(s -> s.getPoint()).max()
				.isPresent()
						? beforeDgreeList.stream().filter(p -> p.getPoint() != null).mapToDouble(s -> s.getPoint())
								.max().getAsDouble()
						: 0.0;
		pointArr[0] = eduMax;
		pointArr[1] = drgee;
		LOG.info("学历最高分：" + eduMax + "," + "学位最高分：" + drgee);
		// 对学位进行排序
		// 取学历/学位的最高分
		if (eduMax > drgee) {
			beforeEducateInfos.get(0).setPoint(eduMax);
		} else {
			beforeEducateInfos.get(0).setPoint(drgee);
		}
		return pointArr;
	}

	/**
	 * 专业技术资格
	 */
	@RequestMapping("/getProTecInfosForSalary")
	@ResponseBody
	public ResultData getProTecInfosForSalary(HttpServletRequest request, String erpNo, String salaryId, String ruleId,
			int year ,boolean salary) {
		ResultData rs = new ResultData();
		try {
			User user = this.getLoginUserInfo(request);
			String startDate = year + "-01-01";
			String endDate = year + "-12-31";
			// 专业技术资格
			List<ProTecInfoVo> proTecInfos ;
			if (salary) {
				//已添加薪档数据
				proTecInfos = userDataInfoService.getProTecInfoByErpNoInSalary(erpNo, salaryId, t_pro_tec_info, ruleId, year, user.getBaseOrgId(),t_pro_tec_info);
			} else {
				proTecInfos = userDataInfoService.getProTecInfoByErpNo(erpNo, salaryId, t_pro_tec_info, ruleId, year, user.getBaseOrgId());
			}

			if (proTecInfos != null && proTecInfos.size() > 0) {
				culProTecPointInfo(user, proTecInfos, erpNo, salaryId, ruleId, year);
				// 判断技能等级,当前年度技能等级
				List<SkillLevelInfoVo> skillLevelInfos = userDataInfoService.getSkillLevelInfoByErpNo(erpNo, salaryId,
						t_skill_level_info, ruleId, year, user.getBaseOrgId());
				if (skillLevelInfos != null && skillLevelInfos.size() > 0) {
					culSkillPointInfo(user, skillLevelInfos, erpNo, salaryId, ruleId, year);

					// 判断只取其中做高分
					// 技能等级最大值
					double s_max = skillLevelInfos.stream().filter(p -> p.getPoint() != null)
							.mapToDouble(s -> s.getPoint()).max().isPresent()
									? skillLevelInfos.stream().filter(p -> p.getPoint() != null)
											.mapToDouble(s -> s.getPoint()).max().getAsDouble()
									: 0.0;

					// 专业技术资格最大值
					double p_max = proTecInfos.stream().filter(p -> p.getPoint() != null).mapToDouble(s -> s.getPoint())
							.max().isPresent()
									? proTecInfos.stream().filter(p -> p.getPoint() != null)
											.mapToDouble(s -> s.getPoint()).max().getAsDouble()
									: 0.0;
					;
					// 如果技术等级取得分最高，专业技术资格不重复加分
					if (s_max > p_max) {
						proTecInfos.stream().forEach(l -> {
							l.setPoint(0.0);
						});
					}
				}
			}
			rs.setSuccess(true);
			rs.setData(proTecInfos);
			LOG.info("查找专业技术资格成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找专业技术资格失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 计算专业技术资格积分
	 *
	 * @param proTecInfos
	 * @param salaryId
	 * @param ruleId
	 * @return
	 */
	private List<ProTecInfoVo> culProTecPointInfo(User user, List<ProTecInfoVo> proTecInfos, String erpNo,
			String salaryId, String ruleId, int year) {
		// 声明返回结果
		List<ProTecInfoVo> resultList = null;
		try {
			// 前年
			int beforeYear = year - 1;
			String beforestartDate = beforeYear + "-01-01";
			String beforendDate = beforeYear + "-12-31";

			// 查询历史专业技术资格
			List<ProTecInfoVo> lastProTecList = userDataInfoService.getProTecInfoByErpNo(erpNo, salaryId,
					t_pro_tec_info, ruleId, year + "-01-01", beforendDate, user.getBaseOrgId());

			// 查询历史技能等级
			List<SkillLevelInfoVo> lastSkillList = userDataInfoService.getSkillLevelInfoByErpNo(erpNo, salaryId,
					t_skill_level_info, ruleId, year + "-01-01", beforendDate, user.getBaseOrgId());

			proTecInfos.stream().forEach(p -> {
				// 判断当前专业的之前的专业
//				List<ProTecInfoVo> list = lastProTecList.stream().filter(l -> l.getSubjSet().equals(p.getSubjSet())).collect(Collectors.toList());
//				list.sort(Comparator.comparing(ProTecInfoVo::getPoint));

				//逻辑由判断之前专业改为判断所有专业 根据积分倒叙
				List<ProTecInfoVo> list = lastProTecList.stream().sorted(Comparator.comparing(ProTecInfoVo::getPoint).reversed()).collect(Collectors.toList());

				if (list != null && list.size() > 0) {
					// 去年取得
					double c = p.getPoint();
					// 之前取得 最高分
					double lc = list.get(0).getPoint();
					if (c > lc) {
						//判断之前有没有同级的技能等级(获取分数相同的技能等级)
						List<SkillLevelInfoVo> skillLevelList = lastSkillList.stream().filter(skillLevelInfoVo -> skillLevelInfoVo.getPoint()==c).collect(Collectors.toList());
						if(CollectionUtils.isNotEmpty(skillLevelList)){
							//对于同时取得中级及以上同级专业技术资格和等级的 ，可增加0.5分（例如：原为中级职称，本年度取得技师，增加0.5分）
							p.setPoint(0.5);
						}else{
							p.setPoint((c - lc));
						}
					}
					else{
						p.setPoint(0.0);
					}
				}
//				else {
//					// 新取得专业技术资格，只新增0.5
//					if (!p.getSubjLevel().equals("其他"))
//						p.setPoint(d_value);
//				}
			});
			// 对积分处理后，进行排序
			resultList = proTecInfos.stream().filter(p -> p.getPoint() != null)
					.sorted(Comparator.comparing(ProTecInfoVo::getPoint).reversed()).collect(Collectors.toList());
			// 清空其余项
			double point = resultList.get(0).getPoint();
			resultList.stream().forEach(p -> {
				p.setPoint(0.0);
			});
			// 在从新赋值
			resultList.get(0).setPoint(point);

		} catch (Exception ex) {
			LOG.error("计算专业技术资格得分失败:" + ex.getMessage());
		}
		return resultList;
	}

	/**
	 * 技能等级
	 */
	@RequestMapping("/getSkillLevelInfoForSalary")
	@ResponseBody
	public ResultData getSkillLevelInfoForSalary(HttpServletRequest request, String erpNo, String salaryId,
			String ruleId, int year,boolean salary) {
		ResultData rs = new ResultData();
		try {
			User user = this.getLoginUserInfo(request);
			String startDate = year + "-01-01";
			String endDate = year + "-12-31";
			List<SkillLevelInfoVo> skillLevelInfos ;
			if (salary) {
				//已添加薪档数据
				skillLevelInfos = userDataInfoService.getSkillLevelInfoByErpNoInSalary(erpNo, salaryId, t_skill_level_info, ruleId, year, user.getBaseOrgId(),t_skill_level_info);
			} else {
				skillLevelInfos = userDataInfoService.getSkillLevelInfoByErpNo(erpNo, salaryId, t_skill_level_info, ruleId, year, user.getBaseOrgId());
			}

			if (skillLevelInfos != null && skillLevelInfos.size() > 0) {
				culSkillPointInfo(user, skillLevelInfos, erpNo, salaryId, ruleId, year);

				// 判断专业技术等级
				List<ProTecInfoVo> proTecInfos ;
				if (salary) {
					//已添加薪档数据
					proTecInfos = userDataInfoService.getProTecInfoByErpNoInSalary(erpNo, salaryId, t_pro_tec_info, ruleId, year, user.getBaseOrgId(),t_pro_tec_info);
				}else {
					proTecInfos = userDataInfoService.getProTecInfoByErpNo(erpNo, salaryId, t_pro_tec_info, ruleId, year, user.getBaseOrgId());
				}

				if (proTecInfos != null && proTecInfos.size() > 0) {
					culProTecPointInfo(user, proTecInfos, erpNo, salaryId, ruleId, year);
				}
				// 判断只取其中做高分
				// 技能等级最大值
				double s_max = skillLevelInfos.stream().filter(p -> p.getPoint() != null).mapToDouble(s -> s.getPoint())
						.max().isPresent()
								? skillLevelInfos.stream().filter(p -> p.getPoint() != null)
										.mapToDouble(s -> s.getPoint()).max().getAsDouble()
								: 0.0;
				// 专业技术资格最大值
				double p_max = proTecInfos.stream().filter(p -> p.getPoint() != null).mapToDouble(s -> s.getPoint())
						.max().isPresent()
								? proTecInfos.stream().filter(p -> p.getPoint() != null).mapToDouble(s -> s.getPoint())
										.max().getAsDouble()
								: 0.0;
				// 如果专业技术取得分最高，技术等级资格不重复加分
				if (s_max <= p_max) {
					skillLevelInfos.stream().forEach(l -> {
						l.setPoint(0.0);
					});
				}

			}
			rs.setSuccess(true);
			rs.setData(skillLevelInfos);
			LOG.info("查找技能等级成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找技能等级失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 计算技能等级积分
	 *
	 * @param skillInfos
	 * @param salaryId
	 * @param ruleId
	 * @return
	 */
	private List<SkillLevelInfoVo> culSkillPointInfo(User user, List<SkillLevelInfoVo> skillInfos, String erpNo,
			String salaryId, String ruleId, int year) {
		// 声明返回结果
		List<SkillLevelInfoVo> resultList = null;
		try {

			// 前年
			int beforeYear = year - 1;
			String beforestartDate = beforeYear + "-01-01";
			String beforendDate = beforeYear + "-12-31";
			// 查询历史技能等级
			List<SkillLevelInfoVo> lastSkillList = userDataInfoService.getSkillLevelInfoByErpNo(erpNo, salaryId,
					t_skill_level_info, ruleId, year + "-01-01", beforendDate, user.getBaseOrgId());


			// 查询历史专业技术资格
			List<ProTecInfoVo> lastProTecList = userDataInfoService.getProTecInfoByErpNo(erpNo, salaryId,
					t_pro_tec_info, ruleId, year + "-01-01", beforendDate, user.getBaseOrgId());

			skillInfos.stream().forEach(p -> {
				// 判断当前专业的之前的专业
//				List<SkillLevelInfoVo> list = lastSkillList.stream().filter(l -> l.getTechType().equals(p.getTechType())).collect(Collectors.toList());
//				list.sort(Comparator.comparing(SkillLevelInfoVo::getPoint));


				// 判断当前专业的之前的专业 改为判断所有专业 根据积分倒叙
				List<SkillLevelInfoVo> list = lastSkillList.stream().sorted(Comparator.comparing(SkillLevelInfoVo::getPoint).reversed()).collect(Collectors.toList());

				if (list != null && list.size() > 0) {
					// 去年取得
					double c = p.getPoint();
					// 前年取得
					double lc = list.get(0).getPoint();
					if (c > lc){
						//判断之前有没有同级的专业技术资格(获取分数相同的专业技术资格)
						List<ProTecInfoVo> protecList = lastProTecList.stream().filter(proTecInfoVo -> proTecInfoVo.getPoint()==c).collect(Collectors.toList());
						if(CollectionUtils.isNotEmpty(protecList)) {
							//对于同时取得中级及以上同级专业技术资格和等级的 ，可增加0.5分（例如：原为中级职称，本年度取得技师，增加0.5分）
							p.setPoint(0.5);
						}else{
							p.setPoint((c - lc));
						}
					}
					else {
							p.setPoint(0.0);
						}
				}
//				else {
//					// 新取得专业技术资格
//					p.setPoint(d_value);
//				}
			});
			// 对积分处理后，进行排序
			resultList = skillInfos.stream().filter(p -> p.getPoint() != null)
					.sorted(Comparator.comparing(SkillLevelInfoVo::getPoint).reversed()).collect(Collectors.toList());
			// 清空其余项
			double point = resultList.get(0).getPoint();
			resultList.stream().forEach(p -> {
				p.setPoint(0.0);
			});
			// 在从新赋值
			resultList.get(0).setPoint(point);

		} catch (Exception ex) {
			LOG.error("计算专业技术资格得分失败:" + ex.getMessage());
		}
		return resultList;
	}

	/**
	 * 工龄
	 */
	@RequestMapping("/getEmployLengthForSalary")
	@ResponseBody
	public ResultData getEmployLengthForSalary(HttpServletRequest request, String erpNo, String ruleId) {
		ResultData rs = new ResultData();
		if (StringUtil.isNullOrEmpty(erpNo) || StringUtil.isNullOrEmpty(ruleId)) {
			rs.setSuccess(false);
			rs.setErrorMsg("参数错误");
			return rs;
		}
		try {
			TEmpBaseInfo tEmpBaseInfo = userDataInfoService.getBaseInfoByErpNo(erpNo);
			User user = this.getLoginUserInfo(request);
			Date jobDate = null;
			if (tEmpBaseInfo != null) {
				jobDate = tEmpBaseInfo.getJobDate();
			}
			Map<String, Object> map = new HashMap<>();
			Calendar can = Calendar.getInstance();
			int currentYear = Integer.valueOf(can.get(Calendar.YEAR));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
			int employLength = 0;
			if (jobDate != null) {
				int date = Integer.valueOf(sdf.format(jobDate));
				employLength = currentYear - date + 1;
			}
			map.put("jobDate", jobDate);
			map.put("employLength", employLength);
			// 查询工龄分数
			List<TRuleElementInfo> ruleElementInfos = ruleElementService.getRuleElementInfoByRuleIdAndMouldId(ruleId,
					t_employ_length, user.getBaseOrgId());
			if (ruleElementInfos != null && ruleElementInfos.size() > 0) {
				map.put("point", ruleElementInfos.get(0).getPoint());
			} else {
				map.put("point", null);
			}
			rs.setSuccess(true);
			rs.setData(map);
			LOG.info("查找工龄成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找工龄失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 专家人才称号
	 */
	@RequestMapping("/getExpertTitleForSalary")
	@ResponseBody
	public ResultData getExpertTitleForSalary(HttpServletRequest request, String erpNo, String salaryId, String ruleId,
			int year,boolean salary) {
		ResultData rs = new ResultData();
		if (StringUtil.isNullOrEmpty(erpNo) || StringUtil.isNullOrEmpty(salaryId) || StringUtil.isNullOrEmpty(ruleId)
				|| year == 0) {
			rs.setSuccess(false);
			rs.setErrorMsg("参数错误");
			return rs;
		}
		try {
			User user = this.getLoginUserInfo(request);
			// 查询近5年内所获所有人才称号
			List<ExpertTitleVo> experts = userDataInfoService.getFiveYearExpertTitleInfoByErpNo(erpNo, salaryId,
					t_expert_title_info, ruleId, year, user.getBaseOrgId());
			Double point = 0.0;
			if (experts != null && experts.size() > 0) {
				for (ExpertTitleVo vo : experts) {
					if (vo.getPoint() != null) {
						point = vo.getPoint();
						break;
					}
				}
			}
			// 查询上一年度所获人才称号
			List<ExpertTitleVo> expertTitleInfos ;
			if (salary) {
				//已添加薪档数据
				expertTitleInfos = userDataInfoService.getExpertTitleInfoByErpNoInSalary(erpNo, salaryId, t_expert_title_info, ruleId, year, user.getBaseOrgId(),t_expert_title_info);
			}else {
				expertTitleInfos = userDataInfoService.getExpertTitleInfoByErpNo(erpNo, salaryId, t_expert_title_info, ruleId, year, user.getBaseOrgId());
			}
			if (expertTitleInfos != null && expertTitleInfos.size() > 0) {
				// 过滤掉分数为null的
				List<ExpertTitleVo> list = expertTitleInfos.stream().filter(p -> (p.getPoint() != null))
						.collect(Collectors.toList());
				// 同一年度同时获得多项人才称号，只取最高分,sql中已按分排序
				for (int i = 0; i < list.size(); i++) {
					if (i > 0) {
						list.get(i).setPoint(0.0);
					} else {
						//如果是级别是其他，不算积分
						if("08".equals(list.get(i).getLevelName())){
							list.get(i).setPoint(0.0);
						}else{
							Double validPoint = list.get(i).getPoint();
							if (validPoint != null && validPoint > point) {
								validPoint = validPoint - point;// 获得分差
								list.get(i).setPoint(validPoint);
							} else {
								list.get(i).setPoint(0.0);
							}
						}

					}
				}
			}
			rs.setSuccess(true);
			rs.setData(expertTitleInfos);
			LOG.info("查找专家人才称号成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找专家人才称号失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 学术成果
	 */
	@RequestMapping("/getAcadeAchiveInfosForSalary")
	@ResponseBody
	public ResultData getAcadeAchiveInfosForSalary(HttpServletRequest request, String erpNo, String salaryId,
			String ruleId, int year,boolean salary) {
		ResultData rs = new ResultData();
		if (StringUtil.isNullOrEmpty(erpNo) || StringUtil.isNullOrEmpty(salaryId) || StringUtil.isNullOrEmpty(ruleId)
				|| year == 0) {
			rs.setSuccess(false);
			rs.setErrorMsg("参数错误");
			return rs;
		}
		try {
			User user = this.getLoginUserInfo(request);
			List<AcadeAchiveVo> acadeAchiveVos ;
			if (salary) {
				//已添加薪档数据
				acadeAchiveVos = userDataInfoService.getAcadeAchiveInfoByErpNoInSalary(erpNo, salaryId, t_acade_achive_info, ruleId, year, user.getBaseOrgId(),t_acade_achive_info);
			} else {
				acadeAchiveVos = userDataInfoService.getAcadeAchiveInfoByErpNo(erpNo, salaryId, t_acade_achive_info, ruleId, year, user.getBaseOrgId());
			}

			if (acadeAchiveVos != null && acadeAchiveVos.size() > 0) {
				for (AcadeAchiveVo vo : acadeAchiveVos) {
					// 主编、独立撰写人、主要撰写人、第一作者、第一撰写人等要赋全部分值，其他作者赋一半分值
					if (!("01,03,04,05,07".contains(vo.getRole()))) {
						vo.setPoint(vo.getPoint() / 2);
					}
				}
			}
			rs.setSuccess(true);
			rs.setData(acadeAchiveVos);
			LOG.info("查找学术成果成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找学术成果失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 发明专利
	 */
	@RequestMapping("/getPatentInfosForSalary")
	@ResponseBody
	public ResultData getPatentInfosForSalary(HttpServletRequest request, String erpNo, String salaryId, String ruleId,
			int year,boolean salary) {
		ResultData rs = new ResultData();
		User user = this.getLoginUserInfo(request);
		if (StringUtil.isNullOrEmpty(erpNo) || StringUtil.isNullOrEmpty(salaryId) || StringUtil.isNullOrEmpty(ruleId)
				|| year == 0) {
			rs.setSuccess(false);
			rs.setErrorMsg("参数错误");
			return rs;
		}
		try {
			List<PatentInfoVo> patentInfos ;
			if (salary) {
				//已添加薪档数据
				patentInfos = userDataInfoService.getPatentInfoByErpNoInSalary(erpNo, salaryId, t_patent_info,ruleId, year, user.getBaseOrgId(),t_patent_info);
			}else {
				patentInfos = userDataInfoService.getPatentInfoByErpNo(erpNo, salaryId, t_patent_info,ruleId, year, user.getBaseOrgId());
			}

			if (patentInfos != null && patentInfos.size() > 0) {
				for (PatentInfoVo vo : patentInfos) {
					String sort = "";
					if (vo.getRank() != null && vo.getRank() != 0) {
						sort = vo.getRank() + "";
						if (vo.getTotal() != 0) {
							sort = sort + "/" + vo.getTotal();
						}
					}
					vo.setSort(sort);

					if(vo.getInventor()!=null){
						String[] inventor = vo.getInventor().split("【");
						vo.setInventor(inventor[0]);
					}
					if (vo.getRank() > 1) {
						if (vo.getPoint() != null) {
							vo.setPoint(vo.getPoint() / 2);
						}
					}
				}
			}
			rs.setSuccess(true);
			rs.setData(patentInfos);
			LOG.info("查找发明专利成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找发明专利失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 科技管理创新
	 */
	@RequestMapping("/getTecManInnovsForSalary")
	@ResponseBody
	public ResultData getTecManInnovsForSalary(HttpServletRequest request, String erpNo, String salaryId, String ruleId,
			int year,boolean salary) {
		ResultData rs = new ResultData();
		if (StringUtil.isNullOrEmpty(erpNo) || StringUtil.isNullOrEmpty(salaryId) || StringUtil.isNullOrEmpty(ruleId)
				|| year == 0) {
			rs.setSuccess(false);
			rs.setErrorMsg("参数错误");
			return rs;
		}
		try {
			User user = this.getLoginUserInfo(request);
			List<TecManInnovVo> tecManInnovVos ;
			if (salary) {
				//已添加薪档数据
				tecManInnovVos = userDataInfoService.getTecManInnovByErpNoInSalary(erpNo, salaryId, t_tec_man_innov, ruleId, year, user.getBaseOrgId(),t_tec_man_innov);
			}else {
				tecManInnovVos = userDataInfoService.getTecManInnovByErpNo(erpNo, salaryId, t_tec_man_innov, ruleId, year, user.getBaseOrgId());
			}
			if (tecManInnovVos != null && tecManInnovVos.size() > 0) {
				for (TecManInnovVo vo : tecManInnovVos) {
					String sort = "";
					if (vo.getRank() != null && vo.getRank() != 0) {
						sort = vo.getRank() + "";
						if (vo.getTotal() != 0) {
							sort = sort + "/" + vo.getTotal();
						}
					}
					vo.setSort(sort);
					// 计算分值
					if (vo.getRank() > 1) {
						vo.setPoint(vo.getPoint() / 2);
					}
				}
				List<String> list = tecManInnovVos.stream()
						.collect(Collectors.groupingBy(vo -> vo.getAchiName(), Collectors.counting())).entrySet()
						.stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey())
						.collect(Collectors.toList());
				if (list.size() > 0) {
					for (String achiName : list) {
						int count = 0;
						List<Double> data = new ArrayList<Double>();
						for (TecManInnovVo vo : tecManInnovVos) {
							if (achiName.equals(vo.getAchiName())) {
								data.add(vo.getPoint());
							}
						}
						double maxPoint = Collections.max(data);
						for (TecManInnovVo vo : tecManInnovVos) {
							if (achiName.equals(vo.getAchiName())) {
								if (maxPoint != vo.getPoint()) {
									vo.setPoint(0.0);
								} else {
									count++;
									if (count > 1) {
										vo.setPoint(0.0);
									}
								}
							}
						}
					}
				}
			}
			rs.setSuccess(true);
			rs.setData(tecManInnovVos);
			LOG.info("查找科技管理创新成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找科技管理创新失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 技艺革新
	 */
	@RequestMapping("/getTecInnovsInfoForSalary")
	@ResponseBody
	public ResultData getTecInnovsInfoForSalary(HttpServletRequest request, String erpNo, String salaryId,
			String ruleId, int year,boolean salary) {
		ResultData rs = new ResultData();
		if (StringUtil.isNullOrEmpty(erpNo) || StringUtil.isNullOrEmpty(salaryId) || StringUtil.isNullOrEmpty(ruleId)
				|| year == 0) {
			rs.setSuccess(false);
			rs.setErrorMsg("参数错误");
			return rs;
		}
		try {
			User user = this.getLoginUserInfo(request);
			List<TecInnovInfoVo> tecInnovInfoVos ;
			if (salary) {
				//已添加薪档数据
				tecInnovInfoVos = userDataInfoService.getTecInnovInfoByErpNoInSalary(erpNo, salaryId, t_tec_innov_info, ruleId, year, user.getBaseOrgId(),t_tec_innov_info);
			}else {
				tecInnovInfoVos = userDataInfoService.getTecInnovInfoByErpNo(erpNo, salaryId, t_tec_innov_info, ruleId, year, user.getBaseOrgId());
			}
			if (tecInnovInfoVos != null && tecInnovInfoVos.size() > 0) {
				for (TecInnovInfoVo vo : tecInnovInfoVos) {
					String sort = "";
					if (vo.getRank() != null && vo.getRank() != 0) {
						sort = vo.getRank() + "";
						if (vo.getTotal() != 0) {
							sort = sort + "/" + vo.getTotal();
						}
					}
					vo.setSort(sort);
					if(vo.getRank()>1){
						vo.setPoint(vo.getPoint() / 2);
					}
				}
			}
			/**   同一成果名称 多个奖项，只取最高分 */
			List<String> list = tecInnovInfoVos.stream()
					.collect(Collectors.groupingBy(vo -> vo.getAchiName(), Collectors.counting())).entrySet()
					.stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey())
					.collect(Collectors.toList());
			if (list.size() > 0) {
				for (String achiName : list) {
					int count = 0;
					List<Double> data = new ArrayList<Double>();
					for (TecInnovInfoVo vo : tecInnovInfoVos) {
						if (achiName.equals(vo.getAchiName())) {
							data.add(vo.getPoint());
						}
					}
					double maxPoint = Collections.max(data);
					for (TecInnovInfoVo vo : tecInnovInfoVos) {
						if (achiName.equals(vo.getAchiName())) {
							if (maxPoint != vo.getPoint()) {
								vo.setPoint(0.0);
							}
						}
					}
				}
			}
			rs.setSuccess(true);
			rs.setData(tecInnovInfoVos);
			LOG.info("查找技艺革新成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找技艺革新失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 专业竞赛考试
	 */
	@RequestMapping("/getTContestInfoForSalary")
	@ResponseBody
	public ResultData getTContestInfoForSalary(HttpServletRequest request, String erpNo, String salaryId, String ruleId,
			int year,boolean salary) {
		ResultData rs = new ResultData();
		if (StringUtil.isNullOrEmpty(erpNo) || StringUtil.isNullOrEmpty(salaryId) || StringUtil.isNullOrEmpty(ruleId)
				|| year == 0) {
			rs.setSuccess(false);
			rs.setErrorMsg("参数错误");
			return rs;
		}
		try {
			User user = this.getLoginUserInfo(request);
			// 竞赛考试
			List<ContestInfoVo> tContestInfos ;
			if (salary) {
				//已添加薪档数据
				tContestInfos = userDataInfoService.getContestInfoByErpNoInSalary(erpNo, salaryId, t_contest_info, ruleId, year, user.getBaseOrgId(),t_contest_info);
			}else {
				tContestInfos = userDataInfoService.getContestInfoByErpNo(erpNo, salaryId,
						t_contest_info, ruleId, year, user.getBaseOrgId());
			}

			if (tContestInfos != null && tContestInfos.size() > 0) {
				List<Double> list = new ArrayList<Double>();
				for (ContestInfoVo vo : tContestInfos) {
					list.add(vo.getPoint());
				}
				double maxPoint = Collections.max(list);
				int count = 0;
				for (ContestInfoVo vo : tContestInfos) {
					if (maxPoint != vo.getPoint()) {
						vo.setPoint(0.0);
					} else {
						count++;
						if (count > 1) {
							vo.setPoint(0.0);
						}
					}
				}
			}
			rs.setSuccess(true);
			rs.setData(tContestInfos);
			LOG.info("查找专业竞赛获奖情况成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找专业竞赛获奖情况失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 个人荣誉
	 */
	@RequestMapping("/getHonorInfosForSalary")
	@ResponseBody
	public ResultData getHonorInfosForSalary(HttpServletRequest request, String erpNo, String salaryId, String ruleId,
			int year,boolean salary) {
		ResultData rs = new ResultData();
		if (StringUtil.isNullOrEmpty(erpNo) || StringUtil.isNullOrEmpty(salaryId) || StringUtil.isNullOrEmpty(ruleId)
				|| year == 0) {
			rs.setSuccess(false);
			rs.setErrorMsg("参数错误");
			return rs;
		}
		try {
			User user = this.getLoginUserInfo(request);
			List<HonorDatasVo> honorDatasVos ;
			if (salary) {
				//已添加薪档数据
				honorDatasVos = userDataInfoService.getHonnorInfoByErpNoInSalary(erpNo, salaryId, t_honor_info, ruleId, year, user.getBaseOrgId(),t_honor_info);
			} else {
				honorDatasVos = userDataInfoService.getHonnorInfoByErpNo(erpNo, salaryId, t_honor_info, ruleId, year, user.getBaseOrgId());
			}
			if (honorDatasVos != null && honorDatasVos.size() > 0) {
				List<Double> list = new ArrayList<Double>();
				for (HonorDatasVo vo : honorDatasVos) {
					list.add(vo.getPoint());
				}
				double maxPoint = Collections.max(list);
				int count = 0;
				for (HonorDatasVo vo : honorDatasVos) {
					//如果是其他，不算积分,或者宣城地市及以下不算积分
					if (maxPoint != vo.getPoint() ||"6".equals(vo.getHonorLevel()) || ("10333706".equals(user.getBaseOrgId()) && ("3".equals(vo.getHonorLevel()) || "4".equals(vo.getHonorLevel())|| "5".equals(vo.getHonorLevel())))) {
						vo.setPoint(0.0);
					} else {
						count++;
						if (count > 1) {
							vo.setPoint(0.0);
						}
					}
				}
			}
			rs.setSuccess(true);
			rs.setData(honorDatasVos);
			LOG.info("查找取得现专业技术资格后荣誉称号成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找取得现后荣誉称号失败！");
			e.printStackTrace();
		}
		return rs;
	}
	/**
	 * 技术标准
	 */
	@RequestMapping("/getTecStandardInfosForSalary")
	@ResponseBody
	public ResultData getTecStandardInfosForSalary(HttpServletRequest request, String erpNo, String salaryId,
												   String ruleId, int year,boolean salary) {
		ResultData rs = new ResultData();
		if (StringUtil.isNullOrEmpty(erpNo) || StringUtil.isNullOrEmpty(salaryId) || StringUtil.isNullOrEmpty(ruleId)
				|| year == 0) {
			rs.setSuccess(false);
			rs.setErrorMsg("参数错误");
			return rs;
		}
		try {
			User user = this.getLoginUserInfo(request);
			List<TecStandardVo> tecStandardInfoVos ;
			if (salary) {
				//已添加薪档数据
				tecStandardInfoVos = userDataInfoService.getTecStandardInfoByErpNoInSalary(erpNo, salaryId, t_tec_standard_info, ruleId, year, user.getBaseOrgId(),t_tec_standard_info);
			} else {
				tecStandardInfoVos = userDataInfoService.getTecStandardInfoByErpNo(erpNo, salaryId, t_tec_standard_info, ruleId, year, user.getBaseOrgId());
			}
			if (tecStandardInfoVos != null && tecStandardInfoVos.size() > 0) {
				for (TecStandardVo vo : tecStandardInfoVos) {
					// 主编要赋全部分值，其他作者赋一半分值
					if (!("1".contains(vo.getRole()))) {
						vo.setPoint(vo.getPoint() / 2);
					}
				}
			}
			rs.setSuccess(true);
			rs.setData(tecStandardInfoVos);
			LOG.info("查找技术标准成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找技术标准失败！");
			e.printStackTrace();
		}
		return rs;
	}
	/**
	 * 年度绩效
	 */
	@RequestMapping("/getYearEffectForSalary")
	@ResponseBody
	public ResultData getYearEffectForSalary(HttpServletRequest request, String erpNo, String ruleId, int year) {
		ResultData rs = new ResultData();
		if (StringUtil.isNullOrEmpty(erpNo) || StringUtil.isNullOrEmpty(ruleId) || year == 0) {
			rs.setSuccess(false);
			rs.setErrorMsg("参数错误");
			return rs;
		}
		try {
			User user = this.getLoginUserInfo(request);
			List<YearEffectVo> yearEffectVos = userDataInfoService.getYearEffectByErpNo(erpNo, t_year_effect_info,ruleId, year, user.getBaseOrgId());
			rs.setSuccess(true);
			if (yearEffectVos != null && yearEffectVos.size() > 0) {
//				rs.setData(yearEffectVos.get(0));
				// 积分调整： 前一年绩效获得A 今年在继续获得A 积分为2.5  后年继续获A还为2.5（如果是其它按照正常取分）
				//A2 B1.5 C1 D0.5
				YearEffectVo yearEffectVo = yearEffectVos.get(0);
				if(null!=yearEffectVo.getPerforGrade() && yearEffectVo.getPerforGrade().equals("A") && year>2020){
					List<YearEffectVo> yearEffectVosTemp = userDataInfoService.getYearEffectByErpNo(erpNo, year-1);
					if(null != yearEffectVosTemp && yearEffectVosTemp.size()>0
							&& null!=yearEffectVosTemp.get(0).getPerforGrade() && yearEffectVosTemp.get(0).getPerforGrade().equals("A")){
						yearEffectVo.setPoint(2.5);
					}
				}
				rs.setData(yearEffectVo);
			}
			LOG.info("查找年度绩效成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找年度绩效失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 员工流动
	 */
	@RequestMapping("/getEmployeeMobilityForSalary")
	@ResponseBody
	public ResultData getEmployeeMobilityForSalary(HttpServletRequest request, String erpNo, String salaryId,
			String ruleId, int year,boolean salary) {
		ResultData rs = new ResultData();
		if (StringUtil.isNullOrEmpty(erpNo) || StringUtil.isNullOrEmpty(salaryId) || StringUtil.isNullOrEmpty(ruleId)
				|| year == 0) {
			rs.setSuccess(false);
			rs.setErrorMsg("参数错误");
			return rs;
		}
		try {
			User user = this.getLoginUserInfo(request);

			List<TEmployeeMobilityVo> EmployeeMobilities = null;
			if (salary){
				//已添加薪档数据
				EmployeeMobilities = userDataInfoService.getEmployeeMobilityByErpNoInSalary(erpNo, salaryId, t_employee_mobility, ruleId, year, user.getBaseOrgId(),t_employee_mobility);
			}else{
				EmployeeMobilities = userDataInfoService.getEmployeeMobilityByErpNo(erpNo, salaryId, t_employee_mobility, ruleId, year, user.getBaseOrgId());
			}

			List<TEmployeeMobilityVo> newEmployeeMobilities = new ArrayList<TEmployeeMobilityVo>();
			if (EmployeeMobilities != null && EmployeeMobilities.size() > 0) {
				// List<Double> list = new ArrayList<Double>();
				for (int i = 0; i < EmployeeMobilities.size(); i++) {
					TEmployeeMobilityVo vo = EmployeeMobilities.get(i);
					Date beginTime = vo.getBeginTime();
					Date endTime = vo.getEndTime();
					if ((beginTime.getYear() + 1900) <= year) {
//							LOG.info("..............................beginTime.getYear()+1900"+(beginTime.getYear()+1900));
//							EmployeeMobilities.remove(i);
//							continue;
						if ((beginTime.getYear() + 1900) < year) {

							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							String beginTimeStr = year + "-01-01";
							beginTime = sdf.parse(beginTimeStr);

						}
						// 去年
						if ((endTime.getYear() + 1900) > year) {
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							String endTimeStr = year + "-12-31";
							endTime = sdf.parse(endTimeStr);
						}
						long daysBetween = (endTime.getTime() - beginTime.getTime()) / (60 * 60 * 24 * 1000);
						if (daysBetween >= 0) {
							// 计算服务了几个月
							long monthCounts = (long) round(daysBetween / 30.0, 0);
							System.out.println("..............................服务月数:i=" + monthCounts);
							LOG.info("..............................服务月数:i=" + monthCounts);
							vo.setPoint(round((monthCounts / 12.0) * vo.getPoint(), 2));
							LOG.info("..............................员工流动分数=" + vo.getPoint());
							newEmployeeMobilities.add(vo);
						}

					}

					// list.add(vo.getPoint());
				}
				// double maxPoint = Collections.max(list);

				// int count = 0;
				// for (TEmployeeMobilityVo vo : EmployeeMobilities) {
				// if (maxPoint != vo.getPoint()) {
				// vo.setPoint(null);
				// } else {
				// count++;
				// if (count > 1) {
				// vo.setPoint(null);
				// }
				// }
				// }
			}
			EmployeeMobilities = newEmployeeMobilities;
			rs.setSuccess(true);
			rs.setData(EmployeeMobilities);
			LOG.info("查找员工流动成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查找员工流动失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 提供精确的小数位四舍五入处理。
	 *
	 * @param v     需要四舍五入的数字
	 *
	 * @param scale 小数点后保留几位
	 *
	 * @return 四舍五入后的结果
	 *
	 */
	public static double round(double v, int scale) {

		if (scale < 0) {

			throw new IllegalArgumentException("The scale must be a positive integer or zero");

		}

		BigDecimal b = new BigDecimal(Double.toString(v));

		BigDecimal one = new BigDecimal("1");

		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();

	}

	/**
	 * 操作可见或隐藏
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("/handleHideOrShowForSenior")
	@ResponseBody
	public ResultData handleHideOrShowForSenior(String erpNo, String id, String isHide, String salaryId) {
		ResultData rs = new ResultData();
		try {
			if (StringUtil.isNullOrEmpty(id) || StringUtil.isNullOrEmpty(isHide)) {
				rs.setSuccess(false);
				rs.setErrorMsg("参数错误");
				return rs;
			}
			tSalaryHandleService.solveData(erpNo, id, isHide, salaryId);
			rs.setSuccess(true);
			rs.setData("操作成功");
			LOG.info("操作成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("操作失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 材料导出到word
	 *
	 * @param response
	 */
	@GetMapping("/exportWord")
	public void exportWord(HttpServletRequest request, HttpServletResponse response, String salaryId, int year) {
		User user = this.getLoginUserInfo(request);
		try {
			if (StringUtil.isNullOrEmpty(user.getFax())) {
				LOG.error("获取当前登录人人资编号失败");
				return;
			}
			LOG.info("薪档调整导出word,查询数据开始");
			// 获取待导出的数据
			SalaryVo modelData = exportWordUserDataInfoService.getModelData(user.getFax(), salaryId, year);
			LOG.info("信息导出word,查询数据完成,开始导出word");
			// 响应页面
			wordExportService.exportWord(response, modelData, user.getName() + "薪档调整信息导出", user.getFax(),
					user.getName());
			LOG.info("个人信息导出word,导出word完成");
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("个人信息导出word异常!!!", e);
		}
	}

	/**
	 * 附件导出
	 *
	 * @param request
	 * @param response
	 * @param sysCode
	 * @param businessNode
	 * @param salaryId
	 */
	@RequestMapping("/downloadAllFiles")
	public void downloadAllFiles(HttpServletRequest request, HttpServletResponse response, String sysCode,
			String businessNode, String salaryId, int year) {
		ResultData rs = new ResultData();
		try {
			User user = this.getLoginUserInfo(request);
			salaryService.downloadFiles(user.getFax(), sysCode, businessNode, request, response, salaryId, year);
			LOG.info("下载附件成功！");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("下载附件失败！");
			e.printStackTrace();
		}
	}

	/**
	 * 分页查询列表:薪档申报查询
	 *
	 * @param page
	 * @return
	 */
	@RequestMapping("/getPageSalaryInfoQuery")
	@ResponseBody
	public ResultData getPageSalaryInfoQuery(Page<TSalaryInfo> page, TSalaryInfo tSalaryInfo, HttpServletRequest request) {
		ResultData rs = new ResultData();
		try {
			User user = this.getLoginUserInfo(request);
			salaryService.getPageSalaryInfoQuery(page, user.getBaseOrgId(), tSalaryInfo.getUserName(),tSalaryInfo.getErpNo(),tSalaryInfo.getYear(),tSalaryInfo.getAuditStatus());
			if (!page.getResult().isEmpty()) {
				page.getResult().forEach(p -> {
					if (null != p.getYear() && p.getYear() == 0) {
						p.setYear(null);
					}
				});
			}
			rs.setData(page);
			LOG.info("查询成功");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("查询失败！");
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 薪档申报查询导出报表
	 */
	@GetMapping("/exportExcelOfSalaryInfoQuery")
	public void exportExcelOfSalaryInfoQuery(HttpServletRequest request, HttpServletResponse response,TSalaryInfo tSalaryInfo) {
		try {
			User user = this.getLoginUserInfo(request);
			//查询要导出的报表数据
			List<TSalaryInfo> list =salaryService.getListSalaryInfoQuery(user.getBaseOrgId(), tSalaryInfo.getUserName(),tSalaryInfo.getErpNo(),tSalaryInfo.getYear(),tSalaryInfo.getAuditStatus());
			String personYearPointDetailHead = "ERP编号,姓名,申报年份,申报状态";
			//获取标题
			String[] personYearPointDetailHeads = personYearPointDetailHead.split(",");
			//sheet名称
			String sheetName = "薪档申报查询导出";
			//获取数据
			String[][] Content = ExcelExportUtil.salaryInfoQuerHead(list, personYearPointDetailHeads);
			//创建workbook
			XSSFWorkbook workbook = new XSSFWorkbook();
			workbook = ExcelExportUtil.exportExcel(workbook, personYearPointDetailHeads, Content, sheetName);//基本信息
			//响应生成excel
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
			LOG.info("开始导出excel报表");
			exportExcel2Browser(response, sheetName + sdf.format(new Date()), workbook);
			LOG.info("导出excel报表成功");
		} catch (Exception e) {
			LOG.error("导出失败");
			e.printStackTrace();
		}
	}

	/**
	 *
	 * 向页面导出excel
	 *
	 * @param response
	 * @param fileName 文件名称
	 * @param workbook 工作簿
	 */
	private void exportExcel2Browser(HttpServletResponse response, String fileName, XSSFWorkbook workbook) {
		OutputStream os = null;
		try {
			// 解决文件乱码
			fileName = URLEncoder.encode(fileName, "UTF8").replaceAll("\\+", "%20");// 其他浏览器
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
			os = response.getOutputStream();
			workbook.write(os);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.flush();
					os.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}


}
